package uia.alumni.profile;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;

import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.form.Form;
import uia.alumni.form.FormField;
import uia.alumni.web.Command;

import static uia.alumni.form.FieldType.*;
import static uia.alumni.profile.Constants.*;
import static uia.alumni.web.Constants.*;

/**
 * Register a profile in the DB.
 * @author Even Åby Larsen (even.larsen@uia.no)
 * @author (edited) Simon Zimmermann.
 */
public class CreateProfile extends Command {

    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "profile.create";
    @PersistenceUnit(name = PERSISTENCE_UNIT)
    private EntityManagerFactory emf;
    @Resource
    private UserTransaction tx;

    public CreateProfile() {
        super(null);
    }

    /**
     * Creates a new user with data from the Register form.
     */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        boolean success = false;
        try {
            // Get Input
            Form form = new Form(request);
            String name = form.newField(FULLNAME, TEXT).getFieldValue();
            String email = form.newField(MAIL, EMAIL).getFieldValue();
            FormField password = form.newField(PASSWORD, PW);

            // Check Password input
            if (form.isValid() && password.getFieldValues().size() == 2) {
                if (password.getFieldValues().get(0).equals(password.getFieldValues().get(1))) {
                    success = true;
                }else{
                    addFormErrors(request, form.addError("Passwords are not the same."));
                }
            }else {
                addFormErrors(request, form.getErrors());
            }

            // See if user with email exists.
            EntityManager em = emf.createEntityManager();
            ProfileManager pm = new ProfileManager(request, em);
            if (!pm.isUniqueEmail(email)) {
                addFormErrors(request, form.addError("Email-address allready exists in database. "));
                success = false;
            }

            // START TRANSACTION IF EVERYTHING WENT OK SO FAR.
            if (success) {
                tx.begin();
                em.joinTransaction();
                User user = new User(email, password.getFieldValue());
                user.setFullName(name);
                user.addRole(Role.member);
                em.persist(user);
                tx.commit();

                // Set session's.
                request.getSession(true).setAttribute(UID, user.getUid());
                request.getSession(true).setAttribute(USER, user);
            }
        } catch (Exception e) {
            addMessage(request, "Creating the profile failed, because " + e.getMessage());
        }

        // Forward the user.
        if (success) forwardTo(ViewProfile.SERVLET_NAME, request, response);
        forwardTo(RegisterProfile.SERVLET_NAME, request, response);
    }
    public final static long serialVersionUID = 1;
}
